var classifyId = "", fillingModel = "", classId = "", templateId = "", templateFileId = "";
var element = "";
layui
    .config({
        base: "../layui/exts/", //静态资源所在路径
    })
    .use(["table", "element", "util"], function () {
        lui = layui;
        var form = layui.form;
        var util = layui.util;
        ($ = layui.$), (element = layui.element);

        form.render();

        table = layui.table;
        openClassify();

        function openClassify() {
            table.render({
                elem: "#classifyTable",
                url: "/basic/getClassifyData",
                contentType: "application/json",
                method: "post",
                height: "full-123",
                loading: true,
                size: "sm",
                cols: [
                    [
                        //标题栏
                        {field: "classifyName", title: "门类名称"},
                        {field: "fillingModel", title: "归档方式", width: 85, templet: "#fillingmodelTpl"},
                        {fixed: "right", title: "操作", width: 55, toolbar: "#classOperationBar"},
                    ],
                ],
                done: function (res, curr, count) {
                    $('.layui-table-view[lay-table-id="classifyTable"]').children(".layui-table-box").children(".layui-table-body").find('table tbody tr[data-index="0"]').click();
                },
            });
        }


        //监听工具条
        table.on("row(classifyTable)", function (obj) {
            var data = obj.data;
            obj.tr.addClass("layui-table-click").siblings().removeClass("layui-table-click");
            classifyId = data.id;
            fillingModel = data.fillingModel;
            if (data.fillingModel <= 3 && data.fillingModel > 0) {
                initFieldTab(data.id, data.fillingModel, data.archivesModel);
                getCodeFormat(data.id);
            } else {
                clearTabs();
            }
        });


        util.on({
            newClassify: function () {
                top.layer.open({
                    type: 2,
                    title: "设置档案门类",
                    content: "./basic/setClassifyData?",
                    area: ["500px", "430px"],
                    shadeClose: false,
                    resize: false,
                    btn: ['<i class="layui-icon">&#xe605;</i> 确定', '<i class="layui-icon">&#x1006;</i> 取消'],
                    yes: function (index, layero) {
                        var iframeWin = layero.find("iframe")[0];
                        if (iframeWin.contentWindow.Buttun_Submit()) {
                            table.reload("classifyTable");
                        }
                    },
                    btn2: function (index) {
                        layer.close(index);
                    },
                });
            },
            newFieldData: function (othis) {
                let idx = $(othis).data("idx");
                top.layer.open({
                    type: 2,
                    title: "设置元数据",
                    content: "./basic/setFieldConfig?id=&&classifyId=" + classifyId + "&fillingModel=" + idx,
                    area: ['500px', $(parent.window).height() + 'px'],
                    shadeClose: false,
                    resize: false,
                    offset: 'rt',
                    btn: ['<i class="layui-icon">&#xe605;</i> 确定', '<i class="layui-icon">&#x1006;</i> 取消'],
                    yes: function (index, layero) {
                        var iframeWin = layero.find("iframe")[0];
                        if (iframeWin.contentWindow.Buttun_Submit()) {
                            console.log(idx);
                            switch (idx) {
                                case 1:
                                    table.reload("recordFieldTable");
                                    break;
                                case 2:
                                    table.reload("filesFieldTable");
                                    break;
                                case 3:
                                    table.reload("projectFieldTable");
                                    break;
                                case 5:
                                    table.reload("dsrFieldTable");
                                    break;
                                case 6:
                                    table.reload("spzFieldTable");
                                    break;
                            }

                        }
                    },
                    btn2: function (index) {
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                    },
                });
            }
        });

        table.on("tool(classifyTable)", function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case "edit":
                    top.layer.open({
                        type: 2,
                        title: "设置档案门类",
                        content: "./basic/setClassifyData?id=" + data.id,
                        area: ["500px", "430px"],
                        shadeClose: false,
                        resize: false,
                        btn: ['<i class="layui-icon">&#xe605;</i> 确定', '<i class="layui-icon">&#x1006;</i> 取消'],
                        yes: function (index, layero) {
                            var iframeWin = layero.find("iframe")[0];
                            if (iframeWin.contentWindow.Buttun_Submit()) {
                                table.reload("classifyTable");
                            }
                        },
                        btn2: function (index) {
                            layer.close(index); //如果设定了yes回调，需进行手工关闭
                        },
                    });
                    return false;
                case "del":
                    top.layer.confirm("确定要删除当前选择的档案门类吗？ ", function (index) {
                        $.ajax({
                            url: "./delClassifyData", //url
                            dataType: "json", //数据格式
                            type: "POST", //请求方式
                            async: false, //是否异步请求
                            data: {id: data.id},
                            success: function (result) {
                                if (result.code == 0) {
                                    table.reload("classifyTable");
                                    layer.close(index);
                                    top.parent.layer.msg(result.message, {icon: 1});
                                } else {
                                    top.parent.layer.alert(result.message, {icon: 2});
                                }
                            },
                        });
                        return false;
                    });
            }
        });

        //监听工具条
        table.on("tool(formatTable)", function (obj) {
            var data = obj.data;

            switch (obj.event) {
                case "addition":
                    var codeModel = parseInt(data.codeModel) - 1;
                    top.layer.open({
                        type: 2,
                        title: "设置档号格式",
                        content: "./basic/archivesCodeFormatList?"
                            + "&classifyId=" + classifyId
                            + "&codeModel=" + codeModel
                            + "&children=1"
                            + "&parentId=" + data.id
                            + "&pid=" + data.pid,
                        area: ["750px", "390px"],
                        shadeClose: false,
                        resize: false,
                        cancel: function () {
                            table.reload("formatTable");
                        }
                    });
                    break;
                case "edit":
                    top.layer.open({
                        type: 2,
                        title: "设置档号格式",
                        content: "./basic/archivesCodeFormatList?"
                            + "&id=" + data.id
                            + "&classifyId=" + classifyId
                            + "&codeModel=" + data.codeModel
                            + "&children=1"
                            + "&parentId=" + data.id
                            + "&pid=" + data.pid,
                        area: ["750px", "390px"],
                        shadeClose: false,
                        resize: false,
                        cancel: function () {
                            table.reload("formatTable");
                        }
                    });
                    break;
                case "del":
                    top.layer.confirm("确定要删除当前选择的档号格式吗？ ", function (index) {
                        $.ajax({
                            url: "./delArchivesCodeFormat", //url
                            dataType: "json", //数据格式
                            type: "POST", //请求方式
                            async: false, //是否异步请求
                            data: {id: data.id},
                            success: function (result) {
                                if (result.code == 0) {
                                    table.reload("formatTable");
                                    layer.close(index);
                                    top.parent.layer.msg(result.message, {icon: 1});
                                } else {
                                    top.parent.layer.alert(result.message, {icon: 2});
                                }
                            },
                        });
                    });
                    break;
            }
            return false;
        });

        //监听文件表工具条
        table.on("tool(recordFieldTable)", function (obj) {
            let data = obj.data;
            switch (obj.event) {
                case "edit":
                    editMetadata(obj, data.id, "1", "recordFieldTable");
                    break;
                case "del":
                    delMetadata(obj, data.issys, data.id);
                    break;
                case "moveUp":
                    moveMetadataPosition(data.id, data.fillingModel, "recordFieldTable", 0);
                    break;
                case "moveDown":
                    moveMetadataPosition(data.id, data.fillingModel, "recordFieldTable", 1);
                    break;
            }
            return false;
        });

        //监听文件表工具条
        table.on("tool(filesFieldTable)", function (obj) {
            let data = obj.data;
            switch (obj.event) {
                case "edit":
                    editMetadata(obj, data.id, "2", "filesFieldTable");
                    break;
                case "del":
                    delMetadata(obj, data.issys, data.id);
                    break;
                case "moveUp":
                    moveMetadataPosition(data.id, data.fillingModel, "filesFieldTable", 0);
                    break;
                case "moveDown":
                    moveMetadataPosition(data.id, data.fillingModel, "filesFieldTable", 1);
                    break;
            }
            return false;
        });

        //监听文件表工具条
        table.on("tool(projectFieldTable)", function (obj) {
            let data = obj.data;
            switch (obj.event) {
                case "edit":
                    editMetadata(obj, data.id, "3", "projectFieldTable");
                    break;
                case "del":
                    delMetadata(obj, data.issys, data.id);
                    break;
                case "moveUp":
                    moveMetadataPosition(data.id, data.fillingModel, "projectFieldTable", 0);
                    break;
                case "moveDown":
                    moveMetadataPosition(data.id, data.fillingModel, "projectFieldTable", 1);
                    break;
            }
            return false;
        });

        function editMetadata(obj, id, model, tableName) {
            top.layer.open({
                type: 2,
                title: "设置元数据",
                content: "./basic/setFieldConfig?id=" + id + "&classifyId=" + classifyId + "&fillingModel=" + model,
                area: ['500px', $(parent.window).height() + 'px'],
                shadeClose: false,
                resize: false,
                offset: 'rt',
                btn: ['<i class="layui-icon">&#xe605;</i> 确定', '<i class="layui-icon">&#x1006;</i> 取消'],
                yes: function (index, layero) {
                    var iframeWin = layero.find("iframe")[0];
                    if (iframeWin.contentWindow.Buttun_Submit()) {
                        table.reload(tableName);
                    }
                },
                btn2: function (index) {
                    layer.close(index);
                },
            });
        }

        function delMetadata(obj, sys, id) {
            if (sys == "1") {
                top.parent.layer.msg("该元数据字段为系统默认字段，不可删除", {icon: 0});
                return false;
            }
            top.layer.confirm("确定要删除当前选择的元数据吗？ ", function (index) {
                $.ajax({
                    url: "./delFieldConfig", //url
                    dataType: "json", //数据格式
                    type: "POST", //请求方式
                    async: false, //是否异步请求
                    data: {id: id, classifyId: classifyId},
                    success: function (result) {
                        if (result.code == 0) {
                            obj.del();
                            top.parent.layer.msg(result.message, {icon: 1});
                        } else {
                            top.parent.layer.alert(result.message, {icon: 2});
                        }
                    },
                });
                return false;
            });
        }

        function moveMetadataPosition(id, fillingModel, tableName, action) {
            $.ajax({
                url: "./moveMetadataPosition", //url
                dataType: "json", //数据格式
                type: "POST", //请求方式
                async: false, //是否异步请求
                data: {id: id, classifyId: classifyId, fillingModel: fillingModel, action: action},
                success: function (result) {
                    if (result.code == 0) {
                        table.reload(tableName);
                    } else {
                        top.parent.layer.alert(result.message, {icon: 2});
                    }
                },
            });
            return false;
        }

        element.on("tab(classifyTab)", function (data) {
            let id = this.getAttribute('lay-id');
            switch (id) {
                case "recordTab":
                    table.reload("recordFieldTable");
                    break;
                case "filesTab":
                    table.reload("filesFieldTable");
                    break;
                case "projectTab":
                    table.reload("projectFieldTable");
                    break;
            }
        });

        //初始化表格
        function initFieldTab(classifyId, fillingModel, archivesModel) {
            clearTabs();
            let focusTab = "", title = "", tableName = "", tabName = "";

            for (let i = fillingModel - 0; i > 0; i--) {
                switch (i) {
                    case 1:
                        title = "件级目录字段";
                        tableName = "recordFieldTable";
                        tabName = "recordTab";
                        break;
                    case 2:
                        title = "卷级目录字段";
                        tableName = "filesFieldTable";
                        tabName = "filesTab";
                        break;
                    case 3:
                        title = "项目目录字段";
                        tableName = "projectFieldTable";
                        tabName = "projectTab";
                        break;
                }
                element.tabAdd("classifyTab", {
                    title: title,
                    content:
                        '<blockquote class="layui-elem-quote-sm" id="toolBar" style="margin-bottom: 5px">' +
                        '<div class="layui-inline" style="margin-bottom: 2px;">' +
                        '<div class="layui-input-block" style="margin-left: 2px; padding: 2px; min-height: 0px; ">' +
                        '<div class="layui-btn-group">' +
                        '<button type="button" class="layui-btn layui-btn-xs layui-btn-primary layui-border-blue"' +
                        'lay-on="newFieldData" data-idx="' + i + '" >' +
                        '<i class="layui-icon layui-icon-addition"></i>新增' +
                        '</button>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        "</blockquote>" +
                        '<table id="' + tableName + '" lay-filter="' + tableName + '"></table>',
                    id: tabName,
                });
                getField(classifyId, i, "#" + tableName);
                if (focusTab == "") {
                    focusTab = tabName;
                }
            }
            switch (archivesModel) {
                case '2':
                    title = "当事人目录字段";
                    tableName = "dsrFieldTable";
                    tabName = "dsrTab";
                    element.tabAdd("classifyTab", {
                        title: title,
                        content:
                            '<blockquote class="layui-elem-quote-sm" id="toolBar" style="margin-bottom: 5px">' +
                            '<div class="layui-inline" style="margin-bottom: 2px;">' +
                            '<div class="layui-input-block" style="margin-left: 2px; padding: 2px; min-height: 0px; ">' +
                            '<div class="layui-btn-group">' +
                            '<button type="button" class="layui-btn layui-btn-xs layui-btn-primary layui-border-blue"' +
                            'lay-on="newFieldData" data-idx="5" >' +
                            '<i class="layui-icon layui-icon-addition"></i>新增' +
                            '</button>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            "</blockquote>" +
                            '<table id="' + tableName + '" lay-filter="' + tableName + '"></table>',
                        id: tabName,
                    });
                    getField(classifyId, 5, "#" + tableName);
                    if (focusTab == "") {
                        focusTab = tabName;
                    }
                    title = "审判组织成员目录字段";
                    tableName = "spzFieldTable";
                    tabName = "spzTab";
                    element.tabAdd("classifyTab", {
                        title: title,
                        content:
                            '<blockquote class="layui-elem-quote-sm" id="toolBar" style="margin-bottom: 5px">' +
                            '<div class="layui-inline" style="margin-bottom: 2px;">' +
                            '<div class="layui-input-block" style="margin-left: 2px; padding: 2px; min-height: 0px; ">' +
                            '<div class="layui-btn-group">' +
                            '<button type="button" class="layui-btn layui-btn-xs layui-btn-primary layui-border-blue"' +
                            'lay-on="newFieldData" data-idx="6" >' +
                            '<i class="layui-icon layui-icon-addition"></i>新增' +
                            '</button>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            "</blockquote>" +
                            '<table id="' + tableName + '" lay-filter="' + tableName + '"></table>',
                        id: tabName,
                    });
                    getField(classifyId, 6, "#" + tableName);
                    if (focusTab == "") {
                        focusTab = tabName;
                    }
                    break;
            }

            if (focusTab != "") {
                element.tabChange("classifyTab", focusTab);
            }
        }

        function getField(classId, fillingModel, elem) {
            table.render({
                elem: elem,
                url: "/basic/getFieldConfigList",
                contentType: "application/json",
                method: "post",
                where: {classify_id: classId, filling_model: fillingModel, sort: "showList"},
                cellMinWidth: 50,
                height: "full-205",
                loading: true,
                size: "sm",
                className: "fieldTable",
                cols: [
                    [
                        //标题栏
                        {field: "fieldTitle", title: "字段标题", width: 120, fixed: "left"},
                        {field: "fieldName", title: "字段名称", width: 150, fixed: "left"},
                        {field: "dataModel", title: "数据类型", width: 100, fixed: "left", templet: "#datamodulTpl"},
                        {field: "datasrcModel", title: "数据来源", width: 80, templet: "#datasrcmodelTpl"},
                        {field: "datasrcName", title: "对应字段", width: 120},
                        {field: "isonly", title: "唯一", width: 50, templet: "#isonlyTpl"},
                        {field: "ismakeonly", title: "组合唯一", width: 70, templet: "#ismakeonlyTpl"},
                        {field: "ismust", title: "必填", width: 50, templet: "#ismustTpl"},
                        {field: "isshowlist", title: "列表显示", width: 70, templet: "#isshowlistTpl"},
                        {field: "showWidth", title: "显示宽度", width: 70},
                        {field: "isShowedit", title: "编辑显示", width: 70, templet: "#isshoweditTpl"},
                        {field: "issearch", title: "检索项", width: 70, templet: "#issearchTpl"},
                        {field: "isfastsearch", title: "快速检索", width: 70, templet: "#isfastsearchTpl"},
                        {field: "isvaguesearch", title: "模糊检索", width: 70, templet: "#isvaguesearchTpl"},
                        {field: "issort", title: "是否排序", width: 70, templet: "#issortTpl"},
                        {field: "sortIdx", title: "排序顺序", width: 70},
                        {field: "isautoinc", title: "自动增长", width: 70, templet: "#isautoincTpl"},
                        {field: "issys", title: "系统字段", width: 70, templet: "#issysTpl"},
                        {field: "canedit", title: "可编辑", width: 60, templet: "#caneditTpl"},
                        {field: "editComponent", title: "编辑组件", width: 100, templet: "#editComponentTpl"},
                        {fixed: "right", title: "操作", width: 110, toolbar: "#operationBar"},
                    ],
                ],
            });
        }

        function getCodeFormat(classifyId) {
            table.render({
                elem: "#formatTable",
                url: "/basic/getArchivesCodeFormat?classifyId=" + classifyId,
                contentType: "application/json",
                method: "post",
                where: {},
                cellMinWidth: 80,
                height: "full-156",
                loading: true,
                size: "sm",
                cols: [
                    [
                        //标题栏
                        {field: "codeFormat", title: "档号格式", templet: "#codeFormatTpl"},
                        {field: "codeModel", title: "档号类型", width: 100, templet: "#codeModelTpl"},
                        {field: "createer", title: "创建人", width: 100},
                        {field: "createDate", title: "创建时间", width: 190},
                        {field: "remark", title: "描述", width: 200},
                        {fixed: "right", title: "操作", width: 105, toolbar: "#codeOperationBar"},
                    ],
                ],
            });
        }
    });


function addArchivesCodeFormat() {
    top.layer.open({
        type: 2,
        title: "设置档号格式",
        content: "./basic/archivesCodeFormatList?classifyId=" + classifyId + "&codeModel=" + fillingModel,
        area: ["750px", "390px"],
        shadeClose: false,
        resize: false,
        cancel: function () {
            table.reload("formatTable");
        }
    });
}

function clearTabs() {
    element.tabDelete("classifyTab", "projectTab");
    element.tabDelete("classifyTab", "filesTab");
    element.tabDelete("classifyTab", "recordTab");
    element.tabDelete("classifyTab", "dsrTab");
    element.tabDelete("classifyTab", "spzTab");
}
